# -*- coding:utf-8 -*-

import redis.asyncio as redis
from redis.exceptions import ConnectionError, TimeoutError

from config.env import RedisConfig
from utils.logger import logger


async def redis_connect():
    if not RedisConfig.redis_enable: return
    redis_pool = redis.ConnectionPool(
        host=RedisConfig.redis_host,  # Redis服务器的地址
        port=RedisConfig.redis_port,  # Redis服务器的端口
        password=RedisConfig.redis_password,  # Redis服务器的密码
        db=RedisConfig.redis_db,  # Redis数据库的索引
        decode_responses=RedisConfig.redis_decode_responses, # 解码响应
        encoding=RedisConfig.redis_encoding # 编码请求
    )
    try:
        client = redis.Redis(connection_pool=redis_pool)
        if await client.ping():
            logger.info("Redis connected")
        return client
    except (ConnectionError):
        logger.info("Redis connection error")
        raise Exception("Redis connection error")
    except (TimeoutError):
        logger.info("Redis connect timeout")
        raise Exception("Redis connect timeout")
    except Exception as e:
        logger.info("Redis error: {e}")
        raise Exception(f"Redis error: {e}")